package com.app.utils.util.view.expression;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.widget.EditText;

import com.app.utils.util.view.expression.bean.MyImageSpan;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 适配表情字符工具
 * @author xuxinghai
 * @date 2016.8.8
 */
public class ExpressionUtil {

    public static Map<String, Integer> name_image_res = new HashMap<String, Integer>();//所有表情集合
    public static String zhengze = "\\[mc_0[0-9]{2}\\]|\\[mc_1[0-9]{2}\\]";//匹配的正则规则 [mc_001]
    public static int match_max_lenth = 8;//匹配的最大长度
    public static String delMacth = "[mc_";//删除匹配的字符

	/**
	 * 对spanableString进行正则判断，如果符合要求，则以表情图片代替
	 * @param context
	 * @param spannableString
	 * @param patten
	 * @param start
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 * @throws NumberFormatException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
    public static void dealExpression(Context context,SpannableString spannableString, Pattern patten, int start) throws SecurityException, NoSuchFieldException, NumberFormatException, IllegalArgumentException, IllegalAccessException {
    	Matcher matcher = patten.matcher(spannableString);
        while (matcher.find()) {
            String key = matcher.group();
            if (matcher.start() < start) {
                continue;
            }
			int resId = name_image_res.get(key);//通过上面匹配得到的字符串来生成图片资源id
//            LogUtils.e("gzq", "resiD = "+ resId);
            if (resId != 0) {
//                Bitmap bitmap = null;
//                try {
//                    bitmap = BitmapFactory.decodeResource(context.getResources(), resId);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    return;
//                }
//                if(bitmap == null){
//                    return;
//                }
//                MyImageSpan imageSpan = new MyImageSpan(context,bitmap);//通过图片资源id来得到bitmap，用一个ImageSpan来包装
                MyImageSpan imageSpan = new MyImageSpan(context, resId);
                int end = matcher.start() + key.length();//计算该图片名字的长度，也就是要替换的字符串的长度
                spannableString.setSpan(imageSpan, matcher.start(), end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);	//将该图片替换字符串中规定的位置中
                if (end < spannableString.length()) {
                	//如果整个字符串还未验证完，则继续。。
                    dealExpression(context,spannableString,  patten, end);
                }
                break;
            }
        }
    }
    
    /**
     * 得到一个SpanableString对象，通过传入的字符串,并进行正则判断
     * @param context
     * @param str
     * @return
     */
    public static SpannableString getExpressionString(Context context,CharSequence str){
        if(str == null){
            str = "";
        }
    	SpannableString spannableString = new SpannableString(str);
        //通过传入的正则表达式来生成一个pattern
        Pattern sinaPatten = Pattern.compile(zhengze, Pattern.CASE_INSENSITIVE);
        try {
            dealExpression(context,spannableString, sinaPatten, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return spannableString;
    }


    /**
     * 匹配一个表情到编辑器中
     * @param context
     * @param msg
     * @param res
     * @param editText
     */
    public static void matchExpression(Context context,String msg,int res,EditText editText){
        if(editText == null || TextUtils.isEmpty(msg)){
            return;
        }
        //获取资源图片显示在 评论中
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), res);
        MyImageSpan imageSpan = new MyImageSpan(context, bitmap);
        SpannableString spannableString = new SpannableString(msg);
        spannableString.setSpan(imageSpan, 0, match_max_lenth, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        editText.append(spannableString);
    }

}